package com.hex.ds.hdrs.log.service;

import com.hex.bigdata.hbda.base.Page;
import com.hex.ds.hdrs.agent.service.AgentConfService;
import com.hex.ds.hdrs.app.service.impl.AppConfService;
import com.hex.ds.hdrs.common.constant.Const;
import com.hex.ds.hdrs.common.utils.BaseUtil;
import com.hex.ds.hdrs.common.utils.HdrsDateUtil;
import com.hex.ds.hdrs.common.utils.MapUtil;
import com.hex.ds.hdrs.log.dao.RunningStateLogDao;
import com.hex.ds.hdrs.log.po.RunningStateLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class RunningStateLogService {

    @Autowired
    private RunningStateLogDao runningStateLogDao;

    @Autowired
    private AgentConfService agentConfService;

    @Autowired
    private AppConfService appConfService;

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    public List<RunningStateLog> queryrunningStateLog(RunningStateLog runningStateLog, Page page) {
        Map map = MapUtil.convertObjToMap(runningStateLog);
        return this.runningStateLogDao.queryrunningStateLog(map, page);
    }

    /**
     * 分页查询
     *
     * @param page
     * @return
     */
    public List<RunningStateLog> selectPages(Page page) {
        log.info("RunningStateLogService的selectPages");
        return this.runningStateLogDao.selectPages(page);
    }

    /**
     * 查看节点运行记录
     *
     * @param agentCode
     * @return
     */
    public List<RunningStateLog> selectAgentStates(String agentCode) {
        log.info("【进入了RunningStateLogService类中的selectAgentStates方法】参数agentCode: {}", agentCode);
        return this.runningStateLogDao.selectAgentStates(agentCode);
    }

    public List<RunningStateLog> findRunningStateLog() {
        return this.findRunningStateLog(new HashMap());
    }

    public List<RunningStateLog> findRunningStateLog(Map paramMap) {
        return this.runningStateLogDao.findRunningStateLog(paramMap);
    }

    public List<RunningStateLog> findNeedSendStateLog(){
        Map paramMap = new HashMap(16);
        paramMap.put("isSend", Const.WARN_NOT_SEND);
        return this.findRunningStateLog(paramMap);
    }

    /**
     * 获取某个用户的运行日志记录
     *
     * @param username
     * @param pageIndex
     * @return
     */
    public List<RunningStateLog> findRunningLogByUser(String username, Integer pageIndex) {
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(10);
        List<String> agentCodeList = this.agentConfService.findAgentCodeByUser(username);
        List<String> appCodeList = this.appConfService.findAppCodeByUser(username);
        if (CollectionUtils.isNotEmpty(agentCodeList) || CollectionUtils.isNotEmpty(appCodeList)) {
            Map map = new HashMap();
            map.put("agentCodeList", agentCodeList);
            map.put("appCodeList", appCodeList);
            return this.runningStateLogDao.qryRunningStateLogByUser(map, page);
        }
        return null;
    }

    /**
     * 通过应用编码查询运行状态日志信息
     *
     * @param
     * @return
     */
    public List<RunningStateLog> findRunningStateLogByAppCode(String appCode, Integer pageIndex) {
        log.info("进入RunningStateLogService的findRunningStateLogByAppCode 参数appCode: {}", appCode);
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(10);
        return this.runningStateLogDao.findRunningStateLogByAppCode(appCode, page);
    }

    /**
     * 新增运行状况日志表
     *
     * @param runningStateLog
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void insert(RunningStateLog runningStateLog) {
        runningStateLog.setPkId(BaseUtil.getPkId());
        this.runningStateLogDao.addRunningStatusLog(runningStateLog);
    }

    public List<RunningStateLog> initMasterRunningStateLog(Integer pageIndex) {
        log.info("进入RunningStateLogService的initMasterRunningStateLog 参数srcType: {}", pageIndex);
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(10);
        return this.runningStateLogDao.initMasterRunningStateLog(null, page);
    }

    public RunningStateLog getLastTimeLog(RunningStateLog log) {
        return this.runningStateLogDao.getLastTimeLog(log);
    }

    public RunningStateLog getLastTimeLog(String srcType, String srcCode, String remindTitle) {
        RunningStateLog log = new RunningStateLog();
        log.setSrcType(srcType);
        log.setSrcCode(srcCode);
        log.setRemindTitle(remindTitle);
        return this.getLastTimeLog(log);
    }

    public RunningStateLog getLastTimeLogByContent(String srcType, String srcCode, String remindContent) {
        RunningStateLog log = new RunningStateLog();
        log.setSrcType(srcType);
        log.setSrcCode(srcCode);
        log.setRemindContent(remindContent);
        return this.getLastTimeLog(log);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void update(String isSend, String sendTime, String pkId) {
        Map map = new HashMap();
        map.put("isSend", isSend);
        map.put("sendTime", sendTime);
        map.put("pkId", pkId);
        this.runningStateLogDao.update(map);
    }

    public boolean checkNeedSaveLog(String srcType, String srcCode, String remindTitle, String remindContent) {
        if (Const.TYPE_CENTER.equals(srcType)) {
            return this.checkCenterNoticeNeedSaveLog(srcType, srcCode, remindTitle);
        }
        if (Const.TYPE_APP.equals(srcType)) {
            return this.checkAppNeedSaveLog(srcType, srcCode, remindTitle, remindContent);
        }
        if (Const.TYPE_AGENT.equals(srcType)) {
            return this.checkAgentNoticeNeedSaveLog(srcType, srcCode, remindTitle);
        }
        return false;
    }

    public boolean checkAppNeedSaveLog(String srcType, String srcCode, String remindTitle, String remindContent) {
        if (remindTitle.contains("执行超时") || Const.TASK_NO_FINISH_OUT_NAME.equals(remindTitle)) {
            return true;
        }
        if (remindTitle.contains("执行失败超时未处理") && this.checkLogExist(srcType, srcCode, remindTitle, remindContent) < 1) {
            return true;
        }
        RunningStateLog lastTimeLog = this.getLastTimeLog(srcType, srcCode, remindTitle);
        if (null == lastTimeLog) {
            return true;
        }
        long nowTimes = System.currentTimeMillis();
        long lastSendTime = HdrsDateUtil.parser(lastTimeLog.getCrtTs(), HdrsDateUtil.YYYY_MM_DDHHMISS).getTime();
        long betterValue = (nowTimes - lastSendTime) / 1000 / 60;
        if (remindTitle.contains(Const.TASK_FAIL_OUT_NAME) && betterValue > 60) {
            return true;
        }
        return false;
    }

    public boolean checkAgentNoticeNeedSaveLog(String srcType, String srcCode, String remindTitle) {
        if (Const.AGENT_WARN_OFF_LINE_NAME.equals(remindTitle)
                || Const.AGENT_CLIENT_CHANGE_NAME.equals(remindTitle)) {
            return true;
        }
        RunningStateLog lastTimeLog = this.getLastTimeLog(srcType, srcCode, remindTitle);
        if (null == lastTimeLog) {
            return true;
        }
        long nowTimes = System.currentTimeMillis();
        long lastSendTime = HdrsDateUtil.parser(lastTimeLog.getCrtTs(), HdrsDateUtil.YYYY_MM_DDHHMISS).getTime();
        long betterValue = (nowTimes - lastSendTime) / 1000 / 60;
        if (Const.AGENT_WARN_CPU_NAME.equals(remindTitle) && betterValue > 60) {
            return true;
        }
        if (Const.AGENT_WARN_RAM_NAME.equals(remindTitle) && betterValue > 60) {
            return true;
        }
        if (Const.AGENT_WARN_DISK_NAME.equals(remindTitle) && betterValue > 60 * 24) {
            return true;
        }
        return false;
    }

    public boolean checkCenterNoticeNeedSaveLog(String srcType, String srcCode, String remindTitle) {

        return true;
    }

    public Integer checkLogExist(String srcType, String srcCode, String remindTitle, String content){
        Map paramMap = new HashMap(16);
        paramMap.put("srcType", srcType);
        paramMap.put("srcCode", srcCode);
        paramMap.put("remindTitle", remindTitle);
        paramMap.put("remind_content", content);
        return this.runningStateLogDao.checkLogExist(paramMap);
    }

    public Integer checkLogExist(Map paramMap) {
        return this.runningStateLogDao.checkLogExist(paramMap);
    }

    /**
     * 判断预警是否需要发送
     * 不发送条件：1、没有发送对象的不发 2、上次发送时间没有超过6个小时的不发送
     * 发送条件：1、必须有接收对象 2、没有发送记录且上次发送时间超过6个小时
     *
     * @param log
     * @return
     */
    public boolean checkNeedSend(RunningStateLog log) {
        // 必须有接收对象
        if (Const.MAIL_NOTICE_OPEN.equals(log.getIsMailNotic()) || Const.SMS_NOTICE_OPEN.equals(log.getIsSmsNotic())) {
            RunningStateLog lastTimeLog = this.getLastTimeLog(log);
            String title = log.getRemindTitle();
            //1、没有发送记录 Agent掉线 Agent上线 Agent汇总
            if (lastTimeLog == null || Const.AGENT_WARN_OFF_LINE_NAME.equals(title)
                    || Const.AGENT_WARN_ON_LINE_NAME.equals(title)) {
                return true;
            }
            long nowTimes = System.currentTimeMillis();
            long lastSendTime = HdrsDateUtil.parser(lastTimeLog.getCrtTs(), HdrsDateUtil.YYYY_MM_DDHHMISS).getTime();
            // 2、上次发送时间超过6个小时
            if ((nowTimes - lastSendTime) > 6 * 60 * 60 * 1000) {
                return true;
            }
        }
        return false;
    }

    public List<RunningStateLog> getAgentOnAndOffline(String startTime,String endTime,List<String> agentCodeList){
        Map paramMap = new HashMap(16);
        paramMap.put("srcType", Const.TYPE_AGENT);
        paramMap.put("remindTitle1", Const.AGENT_WARN_ON_LINE_NAME);
        paramMap.put("remindTitle2", Const.AGENT_WARN_OFF_LINE_NAME);
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        paramMap.put("agentCodeList", agentCodeList);
        return this.runningStateLogDao.getAgentOnAndOffline(paramMap);
    }

    /**
     * @Method: delTaskByDate <br>
     * @Param: [map] <br>
     * @Return: void <br>
     * @Description：根据时间删除运行状况日志数据<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/3 16:31 <br>
     * @Version： V1.0<br>
     */
    public void delTaskByDate(Map map) {
        this.runningStateLogDao.delTaskByDate(map);
    }

    /**
     * @Method: reductionRunningStateLog <br>
     * @Param: [bitchId] <br>
     * @Return: void <br>
     * @Description：还原运行状况日志数据<br>
     * @Author： gc.zuo<br>
     * @Date： 2021/6/3 16:32 <br>
     * @Version： V1.0<br>
     */
    public void reductionRunningStateLog(String bitchId) {
        this.runningStateLogDao.reductionRunningStateLog(bitchId);
    }
}
